/**
 * 
 */
/**
 * 项目名称: base
 * 类名称: package-info
 *
 * 创建人: yyq
 * 创建时间: 2023年3月25日下午3:38:50
 */
package com.team.base.module.controller.wxPay;

import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.team.base.base.config.PayConfig;
import com.team.base.common.utils.IdGenUtil;
import com.team.base.common.utils.wxUtil.PayHttpUtil;
import com.team.base.common.utils.wxUtil.sdk.WXPayConstants.SignType;
import com.team.base.common.utils.wxUtil.sdk.WXPayUtil;
import com.team.base.common.wxPay.Common;
import com.team.base.module.entity.sys.order.Order;
import com.team.base.module.entity.sys.order.Project;
import com.team.base.module.service.sys.order.OrderService;
import com.team.base.module.service.sys.order.ProjectService;
import com.alipay.api.internal.util.StringUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags = { "微信小程序支付" })
@RequestMapping("/api")
@RestController
public class WxPayController {

	@Value("${wx.mini.appid}")
	private String wxspAppid;

	@Value("${wx.mini.mch_id}")
	private String mch_id;

	@Value("${wx.mini.body}")
	private String body;

	@Resource
	private ProjectService projectService;

	@Resource
	private OrderService orderService;

	@PostMapping(value = "/appletPay", produces = "application/json;charset=UTF-8")
	@ApiOperation(value = "小程序支付")
	public void appletPay(@RequestBody String strJson, HttpServletResponse response, HttpServletRequest request) {
		PrintWriter out = null;
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/json; charset=utf-8");

		System.out.println("wxspAppid:" + wxspAppid);

		try {
			// UFT-8解参数
			String strDecoderJson = URLDecoder.decode(strJson, "utf-8");
			// 入参转json格式
			String payItem = request.getParameter("payItem") == null
					? JSON.parseObject(strDecoderJson).getString("payItem")
					: request.getParameter("payItem");
			String money = request.getParameter("money") == null ? JSON.parseObject(strDecoderJson).getString("money")
					: request.getParameter("money");
			String orderNo = request.getParameter("orderNo") == null
					? JSON.parseObject(strDecoderJson).getString("orderNo")
					: request.getParameter("orderNo");
			String openId = request.getParameter("openId") == null
					? JSON.parseObject(strDecoderJson).getString("openId")
					: request.getParameter("openId");
			String spbillCreateIp = request.getRemoteAddr();
			// 创建商品表，获取商品信息
			Project project = new Project();
			// 创建订单表，添加订单信息
			Order order = new Order();

			// 进行信息校验，不符规则抛出异常
			project.setProjectCode(payItem);
			if (project == null || project.getProjectCode() == null || StringUtils.isEmpty(payItem)
					|| StringUtils.isEmpty(money) || StringUtils.isEmpty(orderNo)) {
				response.setStatus(400);
				return;
			}
			project = this.projectService.get(project.getId());
			if (project == null) {
				response.setStatus(400);
				return;
			}

			// 获取配置信息
			Map<String, String> dataWx = new HashMap<>();
			String trueCode = IdGenUtil.uuid();

			// 支付基础信息
			dataWx.put("appid", wxspAppid); // appid
			dataWx.put("mch_id", mch_id);// mch_id
			dataWx.put("nonce_str", trueCode);
			dataWx.put("body", body);
			dataWx.put("out_trade_no", trueCode);
			dataWx.put("total_fee", calculate(money));
			dataWx.put("spbill_create_ip", spbillCreateIp);
			dataWx.put("trade_type", "JSAPI");
			dataWx.put("notify_url", Common.getContextPath(request) + "/pay/notifyWx"); // 回调地址
			dataWx.put("openid", openId);
			String signStr = WXPayUtil.generateSignedXml(dataWx, "f51c83624e0ce422896eab85bc4b87cd");

			Map<String, String> wxMap = PayHttpUtil.http(PayConfig.WX_PAY, signStr);
			Map<String, String> dataWx2 = new HashMap<>();
			dataWx2.put("appId", wxspAppid);
			dataWx2.put("timeStamp", String.valueOf(WXPayUtil.getCurrentTimestamp()));
			dataWx2.put("nonceStr", IdGenUtil.uuid());
			dataWx2.put("package", "prepay_id=" + wxMap.get("prepay_id"));
			dataWx2.put("signType", "MD5");
			String sign = WXPayUtil.generateSignature(dataWx2, "f51c83624e0ce422896eab85bc4b87cd", SignType.MD5);
			dataWx2.put("paySign", sign);

			// 订单表插入信息
			String signStr2 = WXPayUtil.mapToXml(dataWx2);
			order.setMoney(Float.valueOf(money));
			order.setOrderNo(orderNo);
			order.setPayItem(payItem);
			order.setParam(signStr2);

			order.setTrueCode(trueCode);
			out = response.getWriter();
			out.append(JSONObject.toJSONString("order"));
			this.orderService.save(order);

		} catch (Exception e) {
			e.printStackTrace();
			response.setStatus(500);
		}
	}

	/**
	 * 将money 乘100
	 * 
	 * @param money
	 * @return
	 */
	public String calculate(String money) {
		BigDecimal dig = new BigDecimal(money);
		BigDecimal dig1 = new BigDecimal(100);
		dig.add(dig.multiply(dig1));
		Double f = Double.valueOf(dig.multiply(dig1).toString());
		int a = (int) Math.ceil(f);
		return String.valueOf(a);
	}

}